/**
 * 配置管理工具类
 * 用于管理前端配置数据，与后端配置API交互
 */
import configApi from '@/api/config'

class ConfigManager {
  constructor() {
    this.configCache = new Map()
    this.cacheExpireTime = 5 * 60 * 1000 // 5分钟缓存
    this.isInitialized = false
    this.wechatConfig = null
    this.businessConfig = null
  }

  /**
   * 初始化配置管理器
   */
  async initialize() {
    if (this.isInitialized) {
      return
    }

    try {
      console.log('初始化配置管理器...')
      
      // 加载公开配置
      await this.loadPublicConfigs()
      
      this.isInitialized = true
      console.log('配置管理器初始化完成')
    } catch (error) {
      console.error('配置管理器初始化失败:', error)
      throw error
    }
  }

  /**
   * 加载公开配置
   */
  async loadPublicConfigs() {
    try {
      // 并行加载微信配置和业务配置
      const [wechatResult, businessResult] = await Promise.all([
        configApi.getPublicWechatConfig(),
        configApi.getPublicBusinessConfig()
      ])

      if (wechatResult.code === 200) {
        this.wechatConfig = wechatResult.data
        console.log('微信配置加载成功:', this.wechatConfig)
      }

      if (businessResult.code === 200) {
        this.businessConfig = businessResult.data
        console.log('业务配置加载成功:', this.businessConfig)
      }
    } catch (error) {
      console.error('加载公开配置失败:', error)
      // 使用默认配置
      this.wechatConfig = this.getDefaultWechatConfig()
      this.businessConfig = this.getDefaultBusinessConfig()
    }
  }

  /**
   * 获取默认微信配置
   */
  getDefaultWechatConfig() {
    return {
      app_id: '',
      api_base: 'https://api.weixin.qq.com'
    }
  }

  /**
   * 获取默认业务配置
   */
  getDefaultBusinessConfig() {
    return {
      app_name: 'UniApp',
      version: '1.0.0',
      debug_mode: true
    }
  }

  /**
   * 获取微信配置
   */
  getWechatConfig() {
    return this.wechatConfig || this.getDefaultWechatConfig()
  }

  /**
   * 获取业务配置
   */
  getBusinessConfig() {
    return this.businessConfig || this.getDefaultBusinessConfig()
  }

  /**
   * 获取所有配置分组
   */
  async getConfigGroups() {
    try {
      const result = await configApi.getConfigGroups()
      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.message || '获取配置分组失败')
      }
    } catch (error) {
      console.error('获取配置分组失败:', error)
      throw error
    }
  }

  /**
   * 根据分组获取配置
   */
  async getConfigByGroup(groupName) {
    try {
      const result = await configApi.getConfigByGroup(groupName)
      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.message || '获取配置失败')
      }
    } catch (error) {
      console.error(`获取配置分组 ${groupName} 失败:`, error)
      throw error
    }
  }

  /**
   * 根据键名获取配置
   */
  async getConfigByKey(configKey) {
    // 先检查缓存
    const cached = this.configCache.get(configKey)
    if (cached && Date.now() - cached.timestamp < this.cacheExpireTime) {
      return cached.value
    }

    try {
      const result = await configApi.getConfigByKey(configKey)
      if (result.code === 200) {
        const configValue = result.data.config_value
        
        // 缓存结果
        this.configCache.set(configKey, {
          value: configValue,
          timestamp: Date.now()
        })
        
        return configValue
      } else {
        throw new Error(result.message || '获取配置失败')
      }
    } catch (error) {
      console.error(`获取配置 ${configKey} 失败:`, error)
      throw error
    }
  }

  /**
   * 更新配置
   */
  async updateConfig(configKey, configValue) {
    try {
      const result = await configApi.updateConfig(configKey, configValue)
      if (result.code === 200) {
        // 更新缓存
        this.configCache.set(configKey, {
          value: configValue,
          timestamp: Date.now()
        })
        
        console.log(`配置 ${configKey} 更新成功`)
        return true
      } else {
        throw new Error(result.message || '更新配置失败')
      }
    } catch (error) {
      console.error(`更新配置 ${configKey} 失败:`, error)
      throw error
    }
  }

  /**
   * 批量更新配置
   */
  async batchUpdateConfigs(configs) {
    try {
      const result = await configApi.batchUpdateConfigs(configs)
      if (result.code === 200) {
        // 更新缓存
        configs.forEach(config => {
          this.configCache.set(config.config_key, {
            value: config.config_value,
            timestamp: Date.now()
          })
        })
        
        console.log('批量更新配置成功')
        return true
      } else {
        throw new Error(result.message || '批量更新配置失败')
      }
    } catch (error) {
      console.error('批量更新配置失败:', error)
      throw error
    }
  }

  /**
   * 创建新配置
   */
  async createConfig(configData) {
    try {
      const result = await configApi.createConfig(configData)
      if (result.code === 200) {
        console.log('配置创建成功:', result.data)
        return result.data
      } else {
        throw new Error(result.message || '创建配置失败')
      }
    } catch (error) {
      console.error('创建配置失败:', error)
      throw error
    }
  }

  /**
   * 刷新配置缓存
   */
  async refreshCache() {
    try {
      const result = await configApi.refreshCache()
      if (result.code === 200) {
        // 清除本地缓存
        this.configCache.clear()
        
        // 重新加载公开配置
        await this.loadPublicConfigs()
        
        console.log('配置缓存刷新成功')
        return true
      } else {
        throw new Error(result.message || '刷新缓存失败')
      }
    } catch (error) {
      console.error('刷新配置缓存失败:', error)
      throw error
    }
  }

  /**
   * 设置微信配置
   */
  async setWechatConfig() {
    const appId = 'wx40d157e07d5f8688'
    const appSecret = '5128cd90d0ffa51d0da147aaa9be518e'
    try {
      const result = await configApi.setWechatConfig(appId, appSecret)
      if (result.code === 200) {
        // 更新本地微信配置
        this.wechatConfig = {
          app_id: appId,
          api_base: this.wechatConfig?.api_base || 'https://api.weixin.qq.com'
        }
        
        console.log('微信配置设置成功')
        return true
      } else {
        throw new Error(result.message || '设置微信配置失败')
      }
    } catch (error) {
      console.error('设置微信配置失败:', error)
      throw error
    }
  }

  /**
   * 清除缓存
   */
  clearCache() {
    this.configCache.clear()
    console.log('配置缓存已清除')
  }

  /**
   * 获取缓存统计信息
   */
  getCacheStats() {
    return {
      cacheSize: this.configCache.size,
      isInitialized: this.isInitialized,
      wechatConfig: !!this.wechatConfig,
      businessConfig: !!this.businessConfig
    }
  }

  /**
   * 检查配置是否存在
   */
  async hasConfig(configKey) {
    try {
      await this.getConfigByKey(configKey)
      return true
    } catch (error) {
      return false
    }
  }

  /**
   * 获取配置值（带默认值）
   */
  async getConfigValue(configKey, defaultValue = null) {
    try {
      return await this.getConfigByKey(configKey)
    } catch (error) {
      console.warn(`获取配置 ${configKey} 失败，使用默认值:`, defaultValue)
      return defaultValue
    }
  }

  /**
   * 获取多个配置值
   */
  async getMultipleConfigs(configKeys) {
    const results = {}
    
    for (const key of configKeys) {
      try {
        results[key] = await this.getConfigByKey(key)
      } catch (error) {
        console.warn(`获取配置 ${key} 失败:`, error)
        results[key] = null
      }
    }
    
    return results
  }

  /**
   * 批量设置配置
   */
  async setMultipleConfigs(configs) {
    const configList = Object.entries(configs).map(([key, value]) => ({
      config_key: key,
      config_value: value
    }))
    
    return await this.batchUpdateConfigs(configList)
  }
}

// 创建单例实例
const configManager = new ConfigManager()

export default configManager 